package com.cskaoyan.service;

import com.cskaoyan.mapper.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author stone
 * @date 2022/07/08 10:24
 */
@Service
public class AccountServiceImpl implements AccountService{

    @Autowired
    AccountMapper accountMapper;
    //@Autowired
    //SqlSessionFactory sqlSessionFactory;

    //@Transactional(timeout = 5, readOnly = true)
    @Transactional(noRollbackFor = ArithmeticException.class) // 发生异常不回滚 → 依然提交
    @Override
    public void transfer(int fromId, int destId, int money) {
        //SqlSession sqlSession = sqlSessionFactory.openSession();
        //accountMapper = sqlSession.getMapper(AccountMapper.class);

        // 使用accountMapper执行转账业务
        int fromMoney = accountMapper.selectMoneyById(fromId);
        int destMoney = accountMapper.selectMoneyById(destId);

        fromMoney -= money;
        destMoney += money;

        // 发生异常的情况，事务提交了
        accountMapper.updateMoneyById(fromId, fromMoney);
        // 制造异常
        int i = 1 / 0;
        accountMapper.updateMoneyById(destId, destMoney);

    }
}
